#import "Calculator.h"

@implementation Calculator

NSString *lastCommand = nil;
double memory = 0;
double firstValue= 0;
double secondValue= 0;
double result;

- (IBAction)digit:(UIButton*)sender {
	[self assign:sender.currentTitle];
}

- (IBAction)add:(UIButton*)sender {
	firstValue = [display.text doubleValue];
	display.text = @"0";
    lastCommand = @"+";
}

- (IBAction)subtract:(UIButton*)sender {
	firstValue = [display.text doubleValue];
	display.text = @"0";
    lastCommand = @"-";
}

- (IBAction)multiply:(UIButton*)sender {
	firstValue = [display.text doubleValue];
	display.text = @"0";
    lastCommand = @"x";
}

- (IBAction)division:(UIButton*)sender {
	firstValue = [display.text doubleValue];
	display.text = @"0";
    lastCommand = @"/";
}

- (IBAction)positiveNegative:(UIButton*)sender {
    
}

- (IBAction)clear:(UIButton*)sender {
	display.text = @"0";
	firstValue = 0;
	secondValue = 0;
	lastCommand = nil;
}

- (IBAction)memoryClear:(UIButton*)sender {
    
}

- (IBAction)memoryAdd:(UIButton*)sender {
    
}

- (IBAction)memorySubtract:(UIButton*)sender {
    
}

- (IBAction)memoryRecall:(UIButton*)sender {
    
}

- (IBAction)compute:(UIButton*)sender {
	secondValue = [display.text doubleValue];
	if ([lastCommand isEqualToString:@"+"]) {
		result = firstValue+secondValue;
	} else if ([lastCommand isEqualToString:@"-"]) {
		result = firstValue-secondValue;
	} else if ([lastCommand isEqualToString:@"x"]) {
		result = firstValue*secondValue;
	} else if ([lastCommand isEqualToString:@"/"]) {
		result = firstValue/secondValue;
	}
	display.text = [NSString stringWithFormat:@"%lf", result]; 
    lastCommand = @"=";
}

- (void) assign:(NSString*) buttonText {
	if ([buttonText isEqualToString:@"."]) {
		NSRange range = [display.text rangeOfString:@"."];
		if(range.length == 0) {
			display.text = [display.text stringByAppendingString:buttonText];
		}
	} else if([display.text isEqualToString:@"0"]) {
		display.text = buttonText;
	} else if([lastCommand isEqualToString:@"="]) {
		display.text = buttonText;
		lastCommand=nil;
	} else {
		display.text = [display.text stringByAppendingString:buttonText];
	}
}

@end
